#include "studentwindow.h"
#include "videoreceiver.h"
#include "remoteexecutor.h"
#include "screencapture.h"
#include <QDebug>
#include <QApplication>
#include <QScreen>

StudentWindow::StudentWindow(QWidget *parent) : QMainWindow(parent),
    videoReceiver(nullptr), remoteExecutor(nullptr), screenCapture(nullptr),
    isReceiving(false), isRemoteControlEnabled(false), isScreenSharing(false)
{
    setupUI();
    
    // 设置窗口属性
    setWindowTitle("电子教室 - 学生端");
    setMinimumSize(600, 400);
    
    // 获取屏幕尺寸
    QScreen *screen = QApplication::primaryScreen();
    QSize screenSize = screen->size();
    
    // 初始化核心模块
    videoReceiver = new VideoReceiver(this);
    remoteExecutor = new RemoteExecutor(this);
    screenCapture = new ScreenCapture(this);
    
    // 设置参数（硬编码简化）
    videoReceiver->setMulticastAddress("224.1.1.1", 5004);
    videoReceiver->setVideoWidget(videoDisplayArea);
    
    remoteExecutor->setTargetScreenSize(screenSize);
    remoteExecutor->setNetworkInterface(videoReceiver);
    remoteExecutor->setListenPort(5007); // 设置远程控制监听端口，避免与ffplay冲突
    
    // 初始化模块
    videoReceiver->initialize();
    remoteExecutor->initialize();
    screenCapture->initialize();
    
    // 在对象创建后再连接信号
    setupConnections();
}

StudentWindow::~StudentWindow()
{
    if (isReceiving) {
        stopReceiving();
    }
}

void StudentWindow::setupUI()
{
    centralWidget = new QWidget(this);
    setCentralWidget(centralWidget);
    
    mainLayout = new QVBoxLayout(centralWidget);
    
    // 简化的UI布局
    videoDisplayArea = new QWidget(this);
    videoDisplayArea->setMinimumSize(640, 480);
    videoDisplayArea->setStyleSheet("QWidget { background-color: black; border: 1px solid gray; }");
    
    QHBoxLayout *buttonLayout = new QHBoxLayout();
    startReceiveButton = new QPushButton("开始接收", this);
    stopReceiveButton = new QPushButton("停止接收", this);
    stopReceiveButton->setEnabled(false);
    
    remoteControlButton = new QPushButton("启用远程控制", this);
    screenShareButton = new QPushButton("开始屏幕共享", this);
    statusLabel = new QLabel("状态: 未连接", this);
    screenShareStatusLabel = new QLabel("屏幕共享: 未启用", this);
    
    buttonLayout->addWidget(startReceiveButton);
    buttonLayout->addWidget(stopReceiveButton);
    buttonLayout->addWidget(remoteControlButton);
    buttonLayout->addWidget(screenShareButton);
    
    mainLayout->addWidget(videoDisplayArea);
    mainLayout->addLayout(buttonLayout);
    mainLayout->addWidget(statusLabel);
    mainLayout->addWidget(screenShareStatusLabel);
    mainLayout->addStretch();
}

void StudentWindow::setupConnections()
{
    // 核心按钮信号连接
    connect(startReceiveButton, &QPushButton::clicked, this, &StudentWindow::startReceiving);
    connect(stopReceiveButton, &QPushButton::clicked, this, &StudentWindow::stopReceiving);
    connect(remoteControlButton, &QPushButton::clicked, this, &StudentWindow::toggleRemoteControl);
    connect(screenShareButton, &QPushButton::clicked, this, &StudentWindow::toggleScreenSharing);
    
    // 简化的模块信号连接
    connect(videoReceiver, &VideoReceiver::receivingStarted, [this]() { 
        qDebug() << "StudentWindow UI: receivingStarted signal received. Updating status to '已连接'.";
        statusLabel->setText("状态: 已连接");
        startReceiveButton->setEnabled(false);
        stopReceiveButton->setEnabled(true);
    });
    
    connect(videoReceiver, &VideoReceiver::receivingStopped, [this]() { 
        qDebug() << "StudentWindow UI: receivingStopped signal received. Updating status to '未连接'.";
        statusLabel->setText("状态: 未连接");
        startReceiveButton->setEnabled(true);
        stopReceiveButton->setEnabled(false);
    });
    
    connect(videoReceiver, &VideoReceiver::errorOccurred, [this](const QString &error) { 
        qDebug() << "StudentWindow UI: errorOccurred signal received. Updating status to '连接错误'. Error:" << error;
        statusLabel->setText("状态: 连接错误");
        startReceiveButton->setEnabled(true);
        stopReceiveButton->setEnabled(false);
    });
    
    connect(remoteExecutor, &RemoteExecutor::enabled, this, &StudentWindow::onRemoteControlEnabled);
    connect(remoteExecutor, &RemoteExecutor::disabled, this, &StudentWindow::onRemoteControlDisabled);
    connect(remoteExecutor, &RemoteExecutor::commandExecuted, this, &StudentWindow::onRemoteControlCommandExecuted);
    connect(remoteExecutor, &RemoteExecutor::commandReceived, this, &StudentWindow::onRemoteControlCommandReceived);
    connect(remoteExecutor, &RemoteExecutor::errorOccurred, this, &StudentWindow::onRemoteControlError);
    
    // 屏幕共享信号连接
    connect(screenCapture, &ScreenCapture::sharingStarted, this, &StudentWindow::onScreenSharingStarted);
    connect(screenCapture, &ScreenCapture::sharingStopped, this, &StudentWindow::onScreenSharingStopped);
    connect(screenCapture, &ScreenCapture::errorOccurred, this, &StudentWindow::onScreenSharingError);
}

void StudentWindow::startReceiving()
{
    if (isReceiving) return;
    
    qDebug() << "开始接收视频流...";
    
    if (videoReceiver->startReceiving()) {
        isReceiving = true;
        startReceiveButton->setEnabled(false);
        stopReceiveButton->setEnabled(true);
        qDebug() << "视频接收启动成功";
    } else {
        qDebug() << "视频接收启动失败";
    }
}

void StudentWindow::stopReceiving()
{
    if (!isReceiving) return;
    
    qDebug() << "停止接收视频流...";
    
    videoReceiver->stopReceiving();
    
    isReceiving = false;
    startReceiveButton->setEnabled(true);
    stopReceiveButton->setEnabled(false);
    statusLabel->setText("状态: 未连接");
    
    qDebug() << "视频接收已停止";
}

void StudentWindow::toggleRemoteControl()
{
    if (isRemoteControlEnabled) {
        remoteExecutor->disable();
        remoteControlButton->setText("启用远程控制");
        isRemoteControlEnabled = false;
    } else {
        remoteExecutor->enable();
        remoteControlButton->setText("禁用远程控制");
        isRemoteControlEnabled = true;
    }
}

// 远程控制相关槽函数实现
void StudentWindow::onRemoteControlEnabled()
{
    remoteControlButton->setText("禁用远程控制");
    isRemoteControlEnabled = true;
    qDebug() << "学生端远程控制已启用";
}

void StudentWindow::onRemoteControlDisabled()
{
    remoteControlButton->setText("启用远程控制");
    isRemoteControlEnabled = false;
    qDebug() << "学生端远程控制已禁用";
}

void StudentWindow::onRemoteControlCommandExecuted(const QString& commandInfo)
{
    qDebug() << "学生端远程控制命令执行:" << commandInfo;
}

void StudentWindow::onRemoteControlCommandReceived(const QString& commandInfo)
{
    qDebug() << "学生端远程控制命令接收:" << commandInfo;
}

void StudentWindow::onRemoteControlError(const QString& error)
{
    qDebug() << "学生端远程控制错误:" << error;
}

// 屏幕共享相关槽函数实现
void StudentWindow::toggleScreenSharing()
{
    if (isScreenSharing) {
        screenCapture->stopSharing();
        screenShareButton->setText("开始屏幕共享");
        isScreenSharing = false;
    } else {
        // 默认发送到教师端IP，实际使用时需要配置
        screenCapture->startSharing("127.0.0.1", 5006);
        screenShareButton->setText("停止屏幕共享");
        isScreenSharing = true;
    }
}

void StudentWindow::onScreenSharingStarted()
{
    screenShareStatusLabel->setText("屏幕共享: 已启用");
    qDebug() << "屏幕共享已启用";
}

void StudentWindow::onScreenSharingStopped()
{
    screenShareStatusLabel->setText("屏幕共享: 未启用");
    qDebug() << "屏幕共享已禁用";
}

void StudentWindow::onScreenSharingError(const QString& error)
{
    screenShareStatusLabel->setText("屏幕共享: 错误");
    qDebug() << "屏幕共享错误:" << error;
}
